import java.util.Arrays;

/**
 * 数组实现双端队列：
 *   1. 插入元素  add  头、尾 addFirst  addLast  / offerXXX
 *   2. 删除元素     poolFirst  poolLast
 *   3. 获取元素     peekFirst   peekLast
 *   4. 大小        size
 *
 */
public class MyDeque {
    /**
     * 存储元素个数
     */
    private int size;
    /**
     * 存储元素的数组
     */
    private Object[] objects;
    private static final int DEFAULT_LENGTH = 10;

    /**
     * 无参构造
     */
    public MyDeque() {
       objects = new Object[DEFAULT_LENGTH];
    }
    public MyDeque(int length) {
        if (length < 0) {
            throw new RuntimeException("length的长度不能小于0");
        }
        objects = new Object[DEFAULT_LENGTH];
    }
    /**
     * 插入元素
     */
    public void add(Object element) {
        addLast(element);
    }
    public void addFirst(Object element) {
        grow(size + 1);
        System.arraycopy(objects,0,objects,1,size);
        objects[0] = element;
        size++;
    }

    public void addLast(Object element) {
        grow(size + 1);
        objects[size] = element;
        size++;
    }
    /**
     * 扩容
     */
    public void grow(int length) {
        if (length == objects.length) {
            objects = Arrays.copyOf(objects,objects.length + 10);
        }
    }

    /**
     * 删除元素
     *
     * @param
     * @return
     */
    public Object poorFirst() {
        check();
        Object obj = objects[0];
        //去掉第一位
        System.arraycopy(objects,1,objects,0,size-1);
        objects[--size] = null;  //GC
        return obj;
    }
    public Object poorLast() {
        check();
        Object obj = objects[size-1];
        //去掉最后一个
        System.arraycopy(objects,0,objects,0,size-1);
        objects[--size] = null; //GC
        return obj;
    }

    /**
     * 返回元素个数
     * @return
     */
    public int size() {
        return this.size;
    }

    /**
     * 检查队列是否存有元素
     */
    private void check() {
        if (size == 0) {
            throw new RuntimeException("队列里没有元素");
        }
    }

    /**
     * 获取元素
     * @return
     */
    public Object peekFirst() {
        return objects[0];
    }
    public  Object peekLast() {
        return objects[size-1];
    }

    @Override
    public String toString() {
        return "队列里元素有" + size +
                "个，分别是" + Arrays.toString(objects) ;
    }
}
